package com.xiaoyu.lanling.widget.photo

import android.os.Build
import android.os.Bundle
import android.view.View
import android.widget.FrameLayout
import androidx.viewpager.widget.ViewPager.OnPageChangeListener
import com.opensource.svgaplayer.SVGADrawable
import com.xiaoyu.base.data.UserData
import com.xiaoyu.base.event.AppEventBus
import com.xiaoyu.base.event.SimpleEventHandler
import com.xiaoyu.base.model.User
import com.xiaoyu.base.utils.RxUtils
import com.xiaoyu.base.utils.extensions.getViewTag
import com.xiaoyu.base.utils.extensions.setOnClickDebounceListener
import com.xiaoyu.base.utils.extensions.setViewTag
import com.xiaoyu.lanling.R
import com.xiaoyu.lanling.activity.base.AppCompatToolbarActivity
import com.xiaoyu.lanling.common.Constant
import com.xiaoyu.lanling.data.SvgaData
import com.xiaoyu.lanling.event.coin.CoinAccostEvent
import com.xiaoyu.lanling.event.moment.detail.MomentDetailEvent
import com.xiaoyu.lanling.feature.coin.data.CoinData
import com.xiaoyu.lanling.feature.moment.data.MomentData
import com.xiaoyu.lanling.feature.moment.model.MomentItem
import com.xiaoyu.lanling.media.image.ImageViewUtil
import com.xiaoyu.lanling.widget.svga.SvgaBaseCallback
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_moment_photo.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class MomentPhotoActivity : AppCompatToolbarActivity() {
    private val requestTag = Any()
    private var mPhotoViewPager: PhotoViewPager? = null
    private var mSelectedImageUrl: String? = null
    private var mPhotoPagerAdapter: PhotoPagerAdapter? = null
    private var mSvgaDisposable: Disposable? = null
    override fun onCreateSafelyAfterAppFinishInit(savedInstanceState: Bundle?) {
        super.onCreateSafelyAfterAppFinishInit(savedInstanceState)
        setContentView(R.layout.activity_moment_photo)
        initView()
        initBind()
        initData()
        initEvent()
    }

    private fun initEvent() {
        AppEventBus.bindContainerAndHandler(this, object : SimpleEventHandler() {
            @Subscribe(threadMode = ThreadMode.MAIN)
            fun onEvent(event: CoinAccostEvent) {
                showAccostSvga()
            }

            @Subscribe(threadMode = ThreadMode.MAIN)
            fun onEvent(event: MomentDetailEvent) {
                if (event.isFailed) {
                    return
                }
                displayUser(event.moment)
            }
        })
    }

    private fun initBind() {
        close?.setOnClickDebounceListener { finish() }
        accost_svga?.callback = object : SvgaBaseCallback() {
            override fun onFinished() {
                accost_svga?.visibility = View.GONE
            }
        }
        accost.setOnClickListener { v ->
            val user = v.getViewTag<User?>() ?: return@setOnClickListener
            CoinData.accost(requestTag, user.uid)
        }
    }

    override fun isSetRequestedOrientationPortrait(): Boolean {
        return Build.VERSION.SDK_INT != Build.VERSION_CODES.O
    }

    private fun initView() {
        mPhotoViewPager = findViewById(R.id.view_pager)
        mPhotoViewPager?.addOnPageChangeListener(object : OnPageChangeListener {
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
                mPhotoPagerAdapter?.let {
                    indicator_text_view?.text = getString(R.string.moment_photo_view_pager_indicator, (position + 1).toString(), it.count.toString())
                }
            }

            override fun onPageSelected(position: Int) {}
            override fun onPageScrollStateChanged(state: Int) {}
        })
        // NOTE set a nav bar padding
        user_layout.setOnApplyWindowInsetsListener { v, insets ->
            // remember if has deal inset , the accost animation has influence on it
            // so we only do it once
            val handled = v.getViewTag<Boolean>() ?: false
            if (handled) return@setOnApplyWindowInsetsListener insets
            val layoutParams = user_layout.layoutParams as FrameLayout.LayoutParams
            layoutParams.bottomMargin = layoutParams.bottomMargin + insets.systemWindowInsetBottom
            user_layout.layoutParams = layoutParams
            v.setViewTag(true)
            return@setOnApplyWindowInsetsListener insets
        }
    }

    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        if (hasFocus) {
            hideSystemUI()
        }
    }

    private fun hideSystemUI() {
        val decorView = window.decorView
        val uiOptions = (View.SYSTEM_UI_FLAG_IMMERSIVE
                or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN // Hide the nav bar and status bar
                or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                or View.SYSTEM_UI_FLAG_FULLSCREEN)
        decorView.systemUiVisibility = uiOptions
    }

    private fun initData() {
        displayViewPager()
        val feedId = intent.getStringExtra(Constant.IntentKey.KEY_FEED_ID)
        MomentData.getMomentDetail(requestTag, feedId)
    }

    private fun displayUser(moment: MomentItem) {
        ImageViewUtil.loadImage(avatar, moment.avatarLoadParam)
        name.setUser(moment.user)
        tag.text = moment.userTag
        soliloquy.text = moment.soliloquy
        name.setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0, if (moment.verified) R.drawable.icon_verify_verified else 0, 0)
        accost.visibility = if (UserData.getInstance().isSelf(moment.user.uid)) View.GONE else View.VISIBLE
        accost_svga.setViewTag(moment.user)
        accost.setViewTag(moment.user)
    }

    private fun displayViewPager() {
        mSelectedImageUrl = intent.getStringExtra(Constant.IntentKey.KEY_PHOTO_SELECTED_IMAGE_URL)
        val imageUrlList = intent.getStringArrayListExtra(Constant.IntentKey.KEY_PHOTO_IMAGE_URL_LIST)
                ?: return
        mPhotoPagerAdapter = PhotoPagerAdapter(this)
        mPhotoViewPager?.adapter = mPhotoPagerAdapter
        mPhotoPagerAdapter?.setData(imageUrlList)
        try {
            var selected = 0
            val index = imageUrlList.indexOf(mSelectedImageUrl)
            if (index != -1) {
                selected = index
            }
            mPhotoViewPager?.setCurrentItem(selected, false)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun showAccostSvga() {
        accost.isSelected = true
        mSvgaDisposable?.dispose()
        mSvgaDisposable = SvgaData.createTaskFromAsset("accost.svga")
                .compose(RxUtils.ioToMainSingleScheduler())
                .subscribe({ entity ->
                    val drawable = SVGADrawable(entity)
                    accost_svga?.visibility = View.VISIBLE
                    accost_svga?.setImageDrawable(drawable)
                    accost_svga?.loops = 1
                    accost_svga?.startAnimation()
                    mSvgaDisposable?.dispose()
                }, { t -> t.printStackTrace() })
    }

    override fun onDestroy() {
        super.onDestroy()
        RxUtils.disposable(mSvgaDisposable)
    }
}